import { request, USE_MOCK } from './request'

/** 身份类型：商家 / 个人 */
export type DistributorType = 'merchant' | 'user'
/** 打款状态：待打款 / 已打款 */
export type DistributorStatus = 'pending' | 'paid'

/** 打款记录 */
export interface PayHistoryItem {
  id: number | string
  amount: number
  time: string
  remark?: string
}

/** 收款信息 */
export interface WithdrawInfo {
  receiver: string
  account: string // 银行卡号/支付宝/微信号统一放这里
  bank?: string // 银行名称（若是银行卡）
}

/** 分销主体 */
export interface Distributor {
  id: number
  type: DistributorType
  name: string
  phone?: string
  withdrawInfo: WithdrawInfo
  totalAmount: number
  pendingAmount: number
  paidAmount: number
  status: DistributorStatus
  payHistory: PayHistoryItem[]
}

/* ---------------- Mock 数据 ---------------- */
const mockList: Distributor[] = [
  {
    id: 1,
    type: 'merchant',
    name: '张三水果店',
    phone: '18888888888',
    withdrawInfo: {
      receiver: '李四',
      account: '6214 **** 3321',
      bank: '招商银行'
    },
    totalAmount: 3200,
    pendingAmount: 500,
    paidAmount: 2700,
    status: 'pending',
    payHistory: [
      { id: 'NO20250101001', amount: 300, time: '2025-01-03 10:21:00', remark: '' },
      { id: 'NO20241201002', amount: 2400, time: '2024-12-02 09:11:00', remark: '' }
    ]
  },
  {
    id: 2,
    type: 'merchant',
    name: '李四奶茶铺',
    phone: '19999998888',
    withdrawInfo: {
      receiver: '王五',
      account: '6214 **** 4821',
      bank: '上海银行'
    },
    totalAmount: 1800,
    pendingAmount: 0,
    paidAmount: 1800,
    status: 'paid',
    payHistory: [{ id: 'NO20250105001', amount: 1800, time: '2025-01-05 13:20:00', remark: '' }]
  },
  {
    id: 3,
    type: 'user', // 预留个人分销员示例
    name: '王小明',
    phone: '17700002222',
    withdrawInfo: {
      receiver: '王小明',
      account: '6214 **** 8543',
      bank: '河北银行'
    },
    totalAmount: 600,
    pendingAmount: 200,
    paidAmount: 400,
    status: 'pending',
    payHistory: [{ id: 'NO20241228001', amount: 400, time: '2024-12-28 18:00:00', remark: '' }]
  }
]

/** 获取分销主体列表 */
export async function getDistributors(): Promise<Distributor[]> {
  if (USE_MOCK) {
    const data = JSON.parse(JSON.stringify(mockList)) as Distributor[]
    return request<Distributor[]>({ url: '/distribution/list', method: 'GET' }, data)
  }
  // ✅ 真实接口预留
  return request<Distributor[]>({
    url: '/distribution/list',
    method: 'GET'
  })
}

/** 打款完成（把待提现打掉并记账到已提现，同时写入打款记录） */
export async function markPayout(id: number): Promise<boolean> {
  if (USE_MOCK) {
    const idx = mockList.findIndex(x => x.id === id)
    if (idx !== -1) {
      const row = mockList[idx]
      const amount = row.pendingAmount
      if (amount > 0) {
        const now = new Date()
        const pad = (n: number) => String(n).padStart(2, '0')
        const stamp =
          now.getFullYear() +
          pad(now.getMonth() + 1) +
          pad(now.getDate()) +
          pad(now.getHours()) +
          pad(now.getMinutes()) +
          pad(now.getSeconds())
        const recordId = `NO${stamp}${Math.floor(Math.random() * 900 + 100)}`

        // 写入记录
        row.payHistory.unshift({
          id: recordId,
          amount,
          time: `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(
            now.getHours()
          )}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`,
          remark: ''
        })

        // 资金变动
        row.paidAmount += amount
        row.pendingAmount = 0
        row.status = 'paid'
        mockList[idx] = { ...row }
      }
    }
    return request<boolean>({ url: `/distribution/payout/${id}`, method: 'POST' }, true)
  }
  // ✅ 真实接口预留
  return request<boolean>({
    url: `/distribution/payout/${id}`,
    method: 'POST'
  })
}
